package com.example.cxxdemo

import android.os.Bundle
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.cxxdemo.databinding.ActivityMain2Binding

class MainActivity2 : AppCompatActivity(), View.OnClickListener {

    private lateinit var binding: ActivityMain2Binding

    companion object {
        init {
            System.loadLibrary("cxxdemo")// 默认调用:JNI_OnLoad
        }
    }

    //动态注册
    external fun dynamicJavaMethod01()
    external fun dynamicJavaMethod02(str: String): Int

    //c++线程
    external fun nativeThread()

    //释放全局引用
    external fun closeThread()


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMain2Binding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.btRegist1.setOnClickListener(this)
        binding.btRegist2.setOnClickListener(this)
        binding.btJniThread.setOnClickListener(this)
    }

    override fun onDestroy() {
        closeThread()
        super.onDestroy()
    }

    override fun onClick(v: View?) {
        v?.id.let {
            when (it) {
                R.id.btRegist1 -> {
                    dynamicJavaMethod01()
                }
                R.id.btRegist2 -> {
                    val a = dynamicJavaMethod02("我通过动态注册执行了事件2")
                    Log.d("wyb", "接收到native的数据: $a")
                }
                R.id.btJniThread -> {
                    nativeThread()
                }
                else -> {}
            }
        }
    }

    fun showUI() {
        //主线程
        if (Looper.getMainLooper() == Looper.myLooper()) {
            showToast("我是主线中   ${Thread.currentThread().name}")
        } else {//子线程
            runOnUiThread {
                showToast("我是c++创建的子线中工作   ${Thread.currentThread().name}")
            }
        }
    }

    fun showToast(str: String) {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show()
    }

}